package vj.graph;

import java.util.NoSuchElementException;

public class Graph {

	private class Node {
		int v; // v is a node on the adjacency list.
		Node next;

		Node(int x, Node t) {
			v = x;
			next = t;
		}
	}

	private int Vcnt, Ecnt;
	private boolean digraph;
	private Node adj[];

	public Graph(int V, boolean flag) {
		Vcnt = V;
		Ecnt = 0;
		digraph = flag;
		adj = new Node[V + 1];
	}

	public int V() {
		return Vcnt;
	}

	public int E() {
		return Ecnt;
	}

	public boolean directed() {
		return digraph;
	}

	// The new Edge is inserted at the beginning
	// of the appropriate adjacency list, since order doesnt matter
	public int insert(Edge e) {
		int v = e.u, w = e.v;
		adj[v] = new Node(w, adj[v]);
		if (!digraph)
			adj[w] = new Node(v, adj[w]);
		return Ecnt++;
	}

	public AdjList getAdjList(int v) {
		return new AdjList(v);
	}

	public class AdjList {
		private Node current;

		public AdjList(int v) {
			current = adj[v];
		}

		public boolean hasNext() {
			return current != null;
		}

		public int next() {
			if (!hasNext())
				throw new NoSuchElementException();
			int v = current.v;
			current = current.next;
			return v;
		}
	}

}
